﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace B.S.XZYData.Api.Wrter.Controllers
{
    /// <summary>
    /// 上传控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ImgController : ControllerBase
    {
        private readonly IWebHostEnvironment web;

        public ImgController(IWebHostEnvironment web)
        {
            this.web = web;
        }

        [HttpPost]
        public IActionResult UploadImg(IFormFile file)
        {
            string n = Guid.NewGuid().ToString();
            string path = web.WebRootPath + "/Upload/" + n + file.FileName;
            using (FileStream fs = System.IO.File.Create(path))
            {
                file.CopyTo(fs);
                fs.Close();
            }
            return Ok("http://localhost:5090" + "/Upload/" + n + file.FileName);
        }

        /// <summary>
        /// 上传文件接口（支持多种文件类型）
        /// </summary>
        /// <param name="file">上传的文件</param>
        /// <returns>上传结果</returns>
        [HttpPost]
        public IActionResult UploadFile(IFormFile file)
        {
            try
            {
                // 检查文件是否为空
                if (file == null || file.Length == 0)
                {
                    return BadRequest(new { 
                        code = 400, 
                        msg = "请选择要上传的文件", 
                        data = (object)null 
                    });
                }

                // 文件大小限制（10MB）
                const long maxFileSize = 10 * 1024 * 1024;
                if (file.Length > maxFileSize)
                {
                    return BadRequest(new { 
                        code = 400, 
                        msg = "文件大小不能超过10MB", 
                        data = (object)null 
                    });
                }

                // 允许的文件扩展名
                var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif", ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".txt", ".zip", ".rar" };
                var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
                
                if (!allowedExtensions.Contains(fileExtension))
                {
                    return BadRequest(new { 
                        code = 400, 
                        msg = $"不支持的文件类型，允许的文件类型：{string.Join(", ", allowedExtensions)}", 
                        data = (object)null 
                    });
                }

                // 确保Upload目录存在
                var uploadDir = Path.Combine(web.WebRootPath, "Upload");
                if (!Directory.Exists(uploadDir))
                {
                    Directory.CreateDirectory(uploadDir);
                }

                // 生成唯一文件名
                string uniqueId = Guid.NewGuid().ToString("N")[..8]; // 取前8位
                string fileName = $"{uniqueId}_{DateTime.Now:yyyyMMddHHmmss}{fileExtension}";
                string filePath = Path.Combine(uploadDir, fileName);

                // 保存文件
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    file.CopyTo(stream);
                }

                // 构建文件URL
                string fileUrl = $"http://localhost:5090/Upload/{fileName}";

                // 返回成功结果
                return Ok(new { 
                    code = 200, 
                    msg = "文件上传成功", 
                    data = new
                    {
                        fileName = fileName,
                        originalName = file.FileName,
                        fileSize = file.Length,
                        fileExtension = fileExtension,
                        uploadTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                        fileUrl = fileUrl,
                        filePath = $"/Upload/{fileName}"
                    }
                });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { 
                    code = 500, 
                    msg = $"文件上传失败：{ex.Message}", 
                    data = (object)null 
                });
            }
        }

        /// <summary>
        /// 批量上传文件接口
        /// </summary>
        /// <param name="files">上传的文件列表</param>
        /// <returns>批量上传结果</returns>
        [HttpPost]
        public IActionResult UploadMultipleFiles(List<IFormFile> files)
        {
            try
            {
                if (files == null || !files.Any())
                {
                    return BadRequest(new { 
                        code = 400, 
                        msg = "请选择要上传的文件", 
                        data = (object)null 
                    });
                }

                // 限制批量上传文件数量
                const int maxFileCount = 5;
                if (files.Count > maxFileCount)
                {
                    return BadRequest(new { 
                        code = 400, 
                        msg = $"一次最多只能上传{maxFileCount}个文件", 
                        data = (object)null 
                    });
                }

                var uploadResults = new List<object>();
                var failedFiles = new List<string>();

                foreach (var file in files)
                {
                    try
                    {
                        // 调用单文件上传逻辑
                        var result = UploadSingleFile(file);
                        if (result.success)
                        {
                            uploadResults.Add(result.data);
                        }
                        else
                        {
                            failedFiles.Add($"{file.FileName}: {result.message}");
                        }
                    }
                    catch (Exception ex)
                    {
                        failedFiles.Add($"{file.FileName}: {ex.Message}");
                    }
                }

                return Ok(new { 
                    code = 200, 
                    msg = failedFiles.Any() ? "部分文件上传失败" : "所有文件上传成功", 
                    data = new
                    {
                        successCount = uploadResults.Count,
                        failedCount = failedFiles.Count,
                        uploadedFiles = uploadResults,
                        failedFiles = failedFiles
                    }
                });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { 
                    code = 500, 
                    msg = $"批量上传失败：{ex.Message}", 
                    data = (object)null 
                });
            }
        }

        /// <summary>
        /// 单文件上传的私有方法
        /// </summary>
        /// <param name="file">要上传的文件</param>
        /// <returns>上传结果</returns>
        private (bool success, string message, object data) UploadSingleFile(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return (false, "文件为空", null);
            }

            // 文件大小限制（10MB）
            const long maxFileSize = 10 * 1024 * 1024;
            if (file.Length > maxFileSize)
            {
                return (false, "文件大小不能超过10MB", null);
            }

            // 允许的文件扩展名
            var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif", ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".txt", ".zip", ".rar" };
            var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
            
            if (!allowedExtensions.Contains(fileExtension))
            {
                return (false, $"不支持的文件类型：{fileExtension}", null);
            }

            // 确保Upload目录存在
            var uploadDir = Path.Combine(web.WebRootPath, "Upload");
            if (!Directory.Exists(uploadDir))
            {
                Directory.CreateDirectory(uploadDir);
            }

            // 生成唯一文件名
            string uniqueId = Guid.NewGuid().ToString("N")[..8];
            string fileName = $"{uniqueId}_{DateTime.Now:yyyyMMddHHmmss}{fileExtension}";
            string filePath = Path.Combine(uploadDir, fileName);

            // 保存文件
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                file.CopyTo(stream);
            }

            // 构建文件URL
            string fileUrl = $"http://localhost:5090/Upload/{fileName}";

            return (true, "上传成功", new
            {
                fileName = fileName,
                originalName = file.FileName,
                fileSize = file.Length,
                fileExtension = fileExtension,
                uploadTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                fileUrl = fileUrl,
                filePath = $"/Upload/{fileName}"
            });
        }
    }
}
